#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# File  : conftest.py
# Author: wangqingbin8
# Time  : 2020-05-25 16:03:54
import os
import time

import allure
import pytest
from _pytest.runner import runtestprotocol

from base.baseDriver import BaseDriver
from loguru import logger

import sys
import os
path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
rootPath = os.path.split(path)[0]
sys.path.append(rootPath)

driver = None
field = False

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    '''
    hook pytest失败
    :param item:
    :param call:
    :return:
    '''
    # execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()
    os.environ['key'] = item.function.__doc__
    # we only look at actual failing test calls, not setup/teardown
    if rep.when == "call" and rep.failed:
        global field
        field = rep.failed
        mode = "a" if os.path.exists("failures") else "w"
        with open("failures", mode) as f:
            # let's also access a fixture for the fun of it
            if "tmpdir" in item.fixturenames:
                extra = " (%s)" % item.funcargs["tmpdir"]
            else:
                extra = ""
            f.write(rep.nodeid + extra + "\n")
        # pic_info = adb_screen_shot()
        with allure.step('添加失败截图...'):
            allure.attach(driver.get_screenshot_as_png(), "失败截图", allure.attachment_type.PNG)


@pytest.fixture(scope='class')
def start_driver():
    logger.info(25 * "--" + "启动浏览器" + 25 * "--")
    global driver
    if driver is None:
        driver = BaseDriver("chrome").driver
    yield driver
    if not field:
        time.sleep(2)
        driver.quit()
        driver = None
    logger.info(25 * "--" + "关闭浏览器" + 25 * "--")



def pytest_collection_modifyitems(items):
    """
    测试用例收集完成时，将收集到的item的name和nodeid的中文显示在控制台上
所有的测试用例收集完毕后调用, 可以再次过滤或者对它们重新排序
 items （收集的测试项目列表）
    """
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode_escape")
        item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")
